<?php
/**
 * Created by PhpStorm
 * User: honglin
 * Date: 2022/8/9
 * Time: 下午5:44
 */

namespace App\Library\Ocean;

use App\Dao\Ocean\OceanRubbishDao;
use App\Dao\Ocean\OceanUserFishDao;
use App\Dao\Ocean\OceanUserRubbishDao;
use App\Dao\User\UserDao;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Cache\Listener\DeleteListenerEvent;
use Psr\EventDispatcher\EventDispatcherInterface;
use Yj\Tool\Carbon;

class OceanRubbishCreate
{
    protected $num = 3;

    protected $maxNum = 10;

    public function __construct()
    {

    }

    public function run()
    {
        $time = Carbon::now()->startOfDay()->timestamp;
        $userIds = App(UserDao::class)->where('send_rubbish_time', '<', $time)->limit(100)->pluck('uid');
        $userIds->every(function ($userId) {
            $this->SendUserRubbish($userId);
            return true;
        });
    }

    /**
     * @Cacheable(prefix="rubbish", ttl=9000, listener="rubbish")
     */
    protected function getRubbish()
    {
        $ocean_rubbish_ids = App(OceanRubbishDao::class)->pluck('id');
        return $ocean_rubbish_ids;
    }

//    /**
//     * @Inject()
//     * @var EventDispatcherInterface
//     */
//    protected $dispatcher;
//
//    public function clearCacheRubbish()
//    {
//        $this->dispatcher->dispatch(new DeleteListenerEvent('rubbish', []));
//    }

    public function SendUserRubbish($userId)
    {
        $userDao = App(UserDao::class)->where('uid', $userId)->first();
        $userDao->send_rubbish_time = time();
        $userDao->save();

        $count = app(OceanUserRubbishDao::class)->where('user_id', $userId)->count();
        $num = min(max($this->maxNum - $count, 0), $this->num);
        if ($num > 0) {
            $rubbishIds = collect($this->getRubbish())->random($num);
            $insertData = collect($rubbishIds)->transform(function ($rubbishId) use ($userId) {
                return [
                    'update_time' => time(),
                    'create_time' => time(),
                    'ocean_rubbish_id' => $rubbishId,
                    'user_id' => $userId,
                ];
            });
            app(OceanUserRubbishDao::class)->insert($insertData->toArray());
        }
    }

}